package com.ruoyi.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ruoyi.common.core.domain.Ztree;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class InitTree {

    public static JSONArray init(List<Ztree> list, Long pid) {
        List<Ztree> tree = new ArrayList<>();
        list.forEach(ztree -> {
            if (ztree.getpId().equals(pid)) {
                list.remove(ztree);
                tree.add(findChild(list, ztree));
            }
        });
        return JSONArray.parseArray(JSON.toJSONString(tree));
    }

    private static Ztree findChild(List<Ztree> list,Ztree ztree) {
        list.forEach(ztr -> {
            if (ztr.getpId().equals(ztree.getId())) {
                list.remove(ztree);
                ztree.getChildren().add(findChild(list, ztr));
            }
        });
        return ztree;
    }

    public static void main(String[] args) {
        List<Ztree> list = new CopyOnWriteArrayList<>();
        list.add(new Ztree(1L, 0L, "123"));
        list.add(new Ztree(2L, 1L, "456"));
        list.add(new Ztree(3L, 1L, "789"));
        list.add(new Ztree(4L, 2L, "951"));
        list.add(new Ztree(5L, 2L, "753"));
        System.out.println(init(list, 0L));
    }
}
